package com.kcyu.sfherp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kcyu.sfherp.entity.*;
import com.kcyu.sfherp.mapper.ms.*;
import com.kcyu.sfherp.service.ChzdService;
import com.kcyu.sfherp.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags="账单类")
@RequestMapping("/chzd")
public class ChzdController {

    @Autowired
    private ChzdMapper chzdMapper;

    @Autowired
    private ChzdService chzdService;

    @Autowired
    private OrderZdMapper orderZdMapper;

    @Autowired
    private OrderMxMapper orderMxMapper;

    @Autowired
    private ZdHasReadMapper zdHasReadMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ChmxMapper chmxMapper;

    @Autowired
    private JhmxMapper jhmxMapper;

    @RequestMapping(value = "/query",method = {RequestMethod.POST})
    @ApiOperation("根据客户名和时间查账单")
    public Map<Object,Object> queryChzdByCustomName(@RequestBody Map info){
        String khname = (String) info.get("khname");
        String startTime = (String) info.get("startTime");
        String endTime = (String) info.get("endTime");
        List<Chzd> chzds = chzdMapper.queryZDbyCustomNameAndDate(khname, startTime, endTime);

        HashMap<Object, Object> map1 = zdUtils(chzds);

        HashMap<Object, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("data",map1);
        return map;
    }

    @GetMapping("/querydetail/{dh}")
    public Map<Object,Object> queryDetailByDh(@PathVariable String dh){
        List<Chmx> list = chzdService.queryZDDetailByDh(dh);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("data",list);
        return map;
    }

    @RequestMapping(value = "/queryRecentZD", method = {RequestMethod.GET})
    public Map<Object, Object> queryRecentZD(){
        List<Chzd> chzds = chzdMapper.queryRecentZD();
        HashMap<Object, Object> map1 = zdUtils(chzds);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("data",map1);
        return map;
    }

    @RequestMapping(value = "/querythatDayZD", method = {RequestMethod.POST})
    public ResponseResult querythatDayZD(@RequestBody Map info){
        String thatDay = (String) info.get("thatDay");
        List<Chzd> chzds = chzdMapper.queryThatDay(thatDay);
        HashMap<Object, Object> map1 = zdUtils(chzds);
        return new ResponseResult(200, "获取成功", map1);
    }

    @RequestMapping(value = "/querythatDayJH", method = {RequestMethod.POST})
    public ResponseResult querythatDayJH(@RequestBody Map info){
        String thatDay = (String) info.get("thatDay");
        List<Jhzd> jhzds = chzdMapper.queryThatDayJH(thatDay);
        HashMap<Object, Object> map = jhzdUtils(jhzds);
        return new ResponseResult(200, "获取成功", map);
    }

    @GetMapping("/queryJHdetail/{dh}")
    public Map<Object,Object> queryJHDetailByDh(@PathVariable String dh){
        List<CustomHistoryPrice> list = chzdService.queryJHDetailByDh(dh);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("data",list);
        return map;
    }

    @RequestMapping(value = "/queryJH",method = {RequestMethod.POST})
    public ResponseResult queryJhzdByCustomName(@RequestBody Map info){
        String khname = (String) info.get("khname");
        String startTime = (String) info.get("startTime");
        String endTime = (String) info.get("endTime");
        List<Jhzd> jhzds = chzdMapper.queryJHbyCustomNameAndDate(khname, startTime, endTime);
        HashMap<Object, Object> map = jhzdUtils(jhzds);
        return new ResponseResult(200, "获取成功", map);
    }

    @RequestMapping(value="/queryOrderZd", method = {RequestMethod.POST})
    public ResponseResult queryOrderZd(@RequestBody Map info){
        String startTime = (String) info.get("startTime");
        String endTime = (String) info.get("endTime");
        List<OrderZd> orderZds = orderZdMapper.UnionQuery(startTime, endTime);

        return new ResponseResult(200, "获取成功", orderZds);
    }

    @RequestMapping(value="/queryOrderZdWithKhname", method = {RequestMethod.POST})
    public ResponseResult queryOrderZdWithKhname(@RequestBody Map info){
        String startTime = (String) info.get("startTime");
        String endTime = (String) info.get("endTime");
        String khname = (String) info.get("khname");
        List<OrderZd> orderZds = orderZdMapper.UnionQueryWithKhname(startTime, endTime, khname);

        return new ResponseResult(200, "获取成功", orderZds);
    }

    @RequestMapping(value="/queryOrderZdDetail/{dh}", method = {RequestMethod.GET})
    public ResponseResult queryOrderZdDetail(@PathVariable String dh){
        List<OrderDetail> detail = orderDetailMapper.getDetail(dh);

        return new ResponseResult(200, "获取成功", detail);
    }

    @RequestMapping(value="/hasReadZd/{dh}/{dhtype}", method = {RequestMethod.GET})
    public ResponseResult hasReadZd(@PathVariable String dh, @PathVariable String dhtype){
        QueryWrapper<ZdHasRead> wrapper = new QueryWrapper<>();
        wrapper.eq("dh", dh);
        wrapper.eq("dh_type", Integer.parseInt(dhtype));
        ZdHasRead one = zdHasReadMapper.selectOne(wrapper);
        System.out.println(one);

        if(Objects.isNull(one)){
            ZdHasRead zdHasRead = new ZdHasRead();
            zdHasRead.setIsRead(1);
            zdHasRead.setDhType(Integer.parseInt(dhtype));
            zdHasRead.setDh(dh);
            try {
                int insert = zdHasReadMapper.insert(zdHasRead);
            } catch (DuplicateKeyException e){
                System.out.println(e.getMessage());
                return new ResponseResult(400, e.getMessage());
            }
        }else{
            one.setIsRead(1);
            int update = zdHasReadMapper.updateById(one);
            return new ResponseResult(200, "修改成功");
        }

        return new ResponseResult(200, "添加成功");
    }

    @RequestMapping(value="/hasQuestZd/{dh}/{dhtype}", method = {RequestMethod.GET})
    public ResponseResult hasQuestZd(@PathVariable String dh, @PathVariable String dhtype){
        QueryWrapper<ZdHasRead> wrapper = new QueryWrapper<>();
        wrapper.eq("dh", dh);
        wrapper.eq("dh_type", Integer.parseInt(dhtype));
        ZdHasRead one = zdHasReadMapper.selectOne(wrapper);
        System.out.println(one);

        if(Objects.isNull(one)){
            ZdHasRead zdHasRead = new ZdHasRead();
            zdHasRead.setIsRead(2);
            zdHasRead.setDhType(Integer.parseInt(dhtype));
            zdHasRead.setDh(dh);
            try {
                int insert = zdHasReadMapper.insert(zdHasRead);
            } catch (DuplicateKeyException e){
                System.out.println(e.getMessage());
                return new ResponseResult(400, e.getMessage());
            }
        }else{
            one.setIsRead(2);
            int update = zdHasReadMapper.updateById(one);
            return new ResponseResult(200, "修改成功");
        }

        return new ResponseResult(200, "添加成功");
    }

    @RequestMapping(value="/getQuestZD/{dhtype}", method = {RequestMethod.GET})
    public ResponseResult getQuestZD(@PathVariable String dhtype){

        List<Chzd> chzds = null;
        if(dhtype.equals("1")){
            chzds = chzdMapper.queryQuestionZD();
        } else if(dhtype.equals("2")){
            chzds = chzdMapper.queryQuestionJHZD();
        }

        HashMap<Object, Object> map = zdUtils(chzds);

        return new ResponseResult(200, "获取成功", map);
    }

    private HashMap<Object, Object> zdUtils(List<Chzd> chzds){
        List<String> dh = new ArrayList<>();

        if(chzds.isEmpty()){
            HashMap<Object, Object> map = new HashMap<>();
            ArrayList<Object> objects = new ArrayList<>();
            map.put("zd", objects);
            map.put("zd_detail", objects);
            return map;
        }

        chzds.forEach(each ->{
            dh.add(each.getDh());
        });

        // Step2： 获取含这些单号的明细
        QueryWrapper<Chmx> wrapper = new QueryWrapper<>();
        for (int i = 0; i < dh.size(); i++) {
            wrapper.eq("dh", dh.get(i)).or();
        }
        List<Chmx> chmxes = chmxMapper.selectList(wrapper);

        // 分类整合
        Map<String, List<Chmx>> map = new HashMap<>();

        for (Chmx chmx : chmxes) {
            if(Objects.isNull(map.get(chmx.getDh()))){
                List<Chmx> mxlist = new ArrayList<>();
                mxlist.add(chmx);
                map.put(chmx.getDh(), mxlist);
            } else {
                List<Chmx> chmxes1 = map.get(chmx.getDh());
                chmxes1.add(chmx);
                map.put(chmx.getDh(), chmxes1);
            }
        }
        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("zd", chzds);
        map1.put("zd_detail", map);

        return map1;
    }

    private HashMap<Object, Object> jhzdUtils(List<Jhzd> jhzds){
        List<String> dh = new ArrayList<>();

        if(jhzds.isEmpty()){
            HashMap<Object, Object> map = new HashMap<>();
            ArrayList<Object> objects = new ArrayList<>();
            map.put("zd", objects);
            map.put("zd_detail", objects);
            return map;
        }

        jhzds.forEach(each ->{
            dh.add(each.getDh());
        });

        // Step2： 获取含这些单号的明细
        QueryWrapper<Jhmx> wrapper = new QueryWrapper<>();
        for (int i = 0; i < dh.size(); i++) {
            wrapper.eq("dh", dh.get(i)).or();
        }
        List<Jhmx> jhmxes = jhmxMapper.selectList(wrapper);

        // 分类整合
        Map<String, List<Jhmx>> map = new HashMap<>();

        for (Jhmx jhmx : jhmxes) {
            if(Objects.isNull(map.get(jhmx.getDh()))){
                List<Jhmx> mxlist = new ArrayList<>();
                mxlist.add(jhmx);
                map.put(jhmx.getDh(), mxlist);
            } else {
                List<Jhmx> jhmxes1 = map.get(jhmx.getDh());
                jhmxes1.add(jhmx);
                map.put(jhmx.getDh(), jhmxes1);
            }
        }
        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("zd", jhzds);
        map1.put("zd_detail", map);

        return map1;
    }

    @RequestMapping(value = "/getOne",method = {RequestMethod.POST})
    public ResponseResult<Chzd> getOne(@RequestParam String dh){
        QueryWrapper<Chzd> wrapper = new QueryWrapper<>();
        wrapper.eq("dh", dh);
        Chzd chzd = chzdMapper.selectOne(wrapper);
        QueryWrapper<Chmx> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dh", dh);
        List<Chmx> chmxes = chmxMapper.selectList(wrapper1);
        chzd.setChmxList(chmxes);
        return new ResponseResult(200, "success", chzd);
    }

    @PostMapping("/orderGetOne")
    public ResponseResult<OrderZd> orderGetOne(@RequestParam String dh){
        QueryWrapper<OrderZd> wrapper = new QueryWrapper<>();
        wrapper.eq("dh", dh);
        OrderZd orderZd = orderZdMapper.selectOne(wrapper);
        QueryWrapper<OrderMx> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dh", dh);
        List<OrderMx> orderMxes = orderMxMapper.selectList(wrapper1);
        orderZd.setChmxList(orderMxes);
        return new ResponseResult(200, "success", orderZd);
    }
}
